const express = require('express')

const model = require('../db/model')

const router = express.Router()

// 添加一条任务数据
router.post('/addTodo', async (req, res) => {
  const { todoName } = req.body
  try {
    await model.create({ todoName })
    const result = await model.find()
    res.send({ success: true, msg: '添加成功', data: result })
  } catch (error) {
    console.log(error)
    res.send({ success: false, msg: '添加失败,请稍后再试' })
  }
})
// 获取所有任务数据
router.get('/getTodos', async (req, res) => {
  try {
    const todos = await model.find()
    res.send({ success: true, msg: '查询成功', data: todos })
  } catch (error) {
    res.send({ success: false, msg: '查询失败' })
  }
})
// 修改一条任务数据的状态
router.post('/updateTodo', async (req, res) => {
  const { id, targetIsDone } = req.body
  try {
    await model.updateOne({ _id: id }, { $set: { isDone: targetIsDone } })
    const result = await model.find()
    res.send({ success: true, msg: '修改成功', data: result })
  } catch (error) {
    res.send({ success: false, msg: '修改失败' })
  }
})

module.exports = router
